package com.hefan.notify.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Fetch {

    public static HttpClient httpClient;

    static {
        // httpClient
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpConnectionParams.setLinger(params, 0);
        ConnManagerParams.setMaxTotalConnections(params, 1000);
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
        connPerRoute.setDefaultMaxPerRoute(50);
        ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpClient = new DefaultHttpClient(cm, params);
    }
    private static Logger log = LoggerFactory.getLogger(Fetch.class);

    private Integer statusCode = 0;

    public Integer getStatusCode() {
        return statusCode;
    }


    public String read(InputStream is, String encode) {
        try {
            if (is != null) {
                int read = 0;
                byte[] bytes = new byte[10 * 1024];
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                while ((read = is.read(bytes)) >= 0) {
                    byteArrayOutputStream.write(bytes, 0, read);

                }
                is.close();

                return new String(byteArrayOutputStream.toByteArray(), encode);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    public String get(String url, String encode) {

        long begin = System.currentTimeMillis();
        HttpGet httpGet = new HttpGet(url);
        String jsonStr = "";
        HttpResponse res = null;
        int code = 0;
        try {
            httpGet.setHeader("Content-Type", "text/html; charset=" + encode);
            httpGet.setHeader("Connection", "close");

            res = httpClient.execute(httpGet);
            code = res.getStatusLine().getStatusCode();
            jsonStr = new String(EntityUtils.toByteArray(res.getEntity()), encode);

        } catch (ClientProtocolException e) {
            log.error("HttpGet abort : " + e.getMessage());
            httpGet.abort();
        } catch (IOException e) {
            log.error("HttpGet abort : " + e.getMessage());
            httpGet.abort();
        } finally {
            try {
                if (res != null) {
                    log.debug("HttpResponse consumeContent");
                    res.getEntity().consumeContent();
                }
            } catch (IOException e) {
                log.error("-------> Release HTTP connection exception:", e);
            }
        }

        long end = System.currentTimeMillis();
        if(code != 200)
            log.error("HttpGet==>" + url + " [time=" + (end - begin) + "ms, code="+code+"]");
        if((end - begin) > 100)
            log.warn("HttpGet==>" + url + " [time=" + (end - begin) + "ms, code="+code+"]");
        this.statusCode = code;
        return jsonStr;
    }


    public String get(String url) {
        return get(url, "UTF-8");
    }




    /** post方法
     * @param url
     * @param properties
     * @return
     */
    public String post(String url, Map<String,String> properties, List<NameValuePair> params, String encode){
        long begin = System.currentTimeMillis();
        String rs = "";
        HttpPost post = new HttpPost(url);
        HttpEntity entity = null;
        int code = 0;
        try{
            post.setEntity(new UrlEncodedFormEntity(params, encode));
            for(Map.Entry<String, String> entry : properties.entrySet()){
                post.addHeader(entry.getKey(), entry.getValue());
            }
            HttpResponse rsp = httpClient.execute(post);

            code = rsp.getStatusLine().getStatusCode();

            entity = rsp.getEntity();
            rs = new String(EntityUtils.toByteArray(entity), encode);

        } catch (Exception e) {
            if(log.isErrorEnabled())
                log.error(e.getMessage(),e);
            post.abort();
        }finally{
            if(entity!=null)
                try {
                    EntityUtils.consume(entity);
                } catch (IOException e) {

                }
        }

        this.statusCode = code;

        return rs;
    }

    /** post方法
     * @param url
     * @param properties
     * @return
     */
    public String post(String url,Map<String,String> properties,List<NameValuePair> nvps){
        return post(url,properties,nvps,HTTP.UTF_8);
    }

    /**
     * XML BODY方式HTTP请求
     * @param url
     * @param xmlStr
     * @return
     */
    public String postXml(String url,String xmlStr, String encode){
        if (encode == null || encode.equals("")) {
            encode = HTTP.UTF_8;
        }
        String rs = "";
        HttpPost httppost = new HttpPost(url);
        HttpEntity resEntity = null;
        try {
            StringEntity myEntity = new StringEntity(xmlStr, encode);
            httppost.addHeader("Content-Type", "text/xml");
            httppost.setEntity(myEntity);
            HttpResponse response = httpClient.execute(httppost);
            resEntity = response.getEntity();
            //rs=new String(StreamUtils.getBytes(resEntity.getContent()),encode);
            rs = new String(EntityUtils.toByteArray(resEntity), encode);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            httppost.abort();
        } finally {
            if(resEntity != null)
                try {
                    EntityUtils.consume(resEntity);
                } catch (IOException e) {

                }
        }
        return rs;
    }

    /**
     * 重载无编码请求
     * @param url
     * @param xmlStr
     * @return
     */
    public String postXml(String url,String xmlStr) {
        return postXml(url, xmlStr, null);
    }
}
